package com.guldan.core.controller;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import com.guldan.core.redis.CacheService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

/**
 * Created by Silas.
 * Date: 2016/11/10
 * Time: 22:07
 */
public class BaseController {
    protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	public CacheService cacheService;

	protected HttpHeaders getExcelHttpHeaders(String fileNm) throws UnsupportedEncodingException{
		HttpHeaders headers = new HttpHeaders();  
	    headers.setContentType(MediaType.MULTIPART_FORM_DATA);  
	    headers.setContentDispositionFormData("attachment",  new String(fileNm.getBytes("utf-8"),"iso-8859-1"));  
	    return headers;
	}

	protected ResponseEntity<byte[]> downloadExcel(String fileNm, String downFileNm) throws IOException{
		FileInputStream fis = new FileInputStream(new File(fileNm));
		BufferedInputStream bis=new BufferedInputStream(fis);
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		int c=bis.read();
		while(c!=-1){
			baos.write(c);
			c=bis.read();
		}
		bis.close();
		fis.close();
	    ResponseEntity<byte[]> responseEntity =  new ResponseEntity<byte[]>( baos.toByteArray(),getExcelHttpHeaders(downFileNm.concat(".xlsx")), HttpStatus.CREATED);
	    baos.flush();
	    baos.close();
	    return responseEntity; 
	}

}
